package leetcode.code0590;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import leetcode.helper.HelpDebug;
import leetcode.helper.tree.Node;

public class Solution {

	public List<Integer> postorder(Node root) {
		List<Integer> ans = new ArrayList<>();
		if (root == null) {
			return ans;
		}
		Stack<Node> stack = new Stack<>();
		stack.add(root);
		while (!stack.isEmpty()) {
			Node cur = stack.pop();
			List<Node> children = cur.children;
			if (children == null || children.size() == 0) {
				ans.add(cur.val);
			} else {
				cur.children = null;
				stack.add(cur);
				for (int i = children.size() - 1; i >= 0; i--) {
					stack.add(children.get(i));
				}
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.postorder(Node.array2tree(HelpDebug.str2array4("[1,null,3,2,4,null,5,6]")));
	}

}
